import { reqCategory1List,reqCategory2List,reqCategory3List } from "@/api"
import Vue from "vue"
const state = {
    //一级分类列表
    Category1List : [],
}
const mutations = {
    //1.给一级分类category1List设置一个新值
   setCategory1List(state,payload){
      state.Category1List = payload.Category1List 
      //顺便给category1List数组中每一个对象都添加一个children属性
      state.Category1List.forEach(item=>{
        Vue.set(item,"children",[])
      })
      
   },
   //1.给一级分类category1List的children设置二级分类
   setCategory2List(state,payload){
    state.Category1List[payload.nowCategoryIndex].children = payload.result
   }
}
const actions = {
    //1.获取1级分类的的列表
   async getCategory1List({commit}){
     const result = await reqCategory1List()
     commit("setCategory1List",{ Category1List : result}) 
    },

    // 2.获取2级分类
    async getCategory2List(store,categoryId){
        //获取触发的一级列表的值
        const nowCategory = store.state.Category1List.find(item=>item.id === categoryId)
        //获取触发的一级列表的下标
        const nowCategoryIndex = store.state.Category1List.findIndex(item=>item.id === categoryId)

        //如果当前一级分类没有children属性,则说明没有发过当前id的二级分类请求,则需要重新发送请求
        if(nowCategory.children.length !== 0)return
        const result = await reqCategory2List(categoryId)
         const resArr = []
        result.forEach((item)=>{
            const category3Promise = reqCategory3List(item.id)
            resArr.push(category3Promise)
        })

        //把收集所有当前二级中的三级列表的请求所在的数组,使用Promise.all进行并发处理
        //Promise.all返回promise实例,如果接受的参数中所有的promise都成功,则all方法返回的promise就成功,值为所有结果值组成的数组
       const category3Result = await Promise.all(resArr)
       category3Result.forEach((item,index)=>{
            result[index].children = item
       })
        //提交mutation进行修改数据
        store.commit("setCategory2List",{nowCategoryIndex,result})
    }
}
const getters = {}

export default {
    namespaced:true,
    state,
    mutations,
    actions,
    getters
}